package cn.lblbc.appassit

import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.provider.DocumentsContract
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import cn.lblbc.appassit.utils.FileUtils
import cn.lblbc.appassit.utils.SharedPreferencesHelper

class SettingsActivity : AppCompatActivity() {

    private lateinit var llExportDirectory: LinearLayout
    private lateinit var aiProgrammingLayout: LinearLayout
    private lateinit var tvExportDirectorySummary: TextView

    private val sharedPreferencesHelper by lazy { SharedPreferencesHelper(this) }

    // 文件选择器结果回调
    private val directoryPickerLauncher = registerForActivityResult(
        ActivityResultContracts.StartActivityForResult()
    ) { result ->
        if (result.resultCode == Activity.RESULT_OK) {
            result.data?.data?.let { uri ->
                val directoryPath = getDirectoryPathFromUri(uri)
                if (directoryPath != null) {
                    sharedPreferencesHelper.setExportDirectory(directoryPath)
                    loadCurrentSettings()
                    Toast.makeText(this, R.string.directory_selected, Toast.LENGTH_SHORT).show()
                } else {
                    Toast.makeText(this, R.string.invalid_directory, Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_settings)

        setSupportActionBar(findViewById(R.id.toolbar))
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        supportActionBar?.title = getString(R.string.settings_title)

        initializeViews()
        loadCurrentSettings()
        setupListeners()
    }

    private fun initializeViews() {
        llExportDirectory = findViewById(R.id.ll_export_directory)
        aiProgrammingLayout = findViewById(R.id.aiProgrammingLayout)
        tvExportDirectorySummary = findViewById(R.id.tv_export_directory_summary)
    }

    private fun loadCurrentSettings() {
        val currentDirectory = sharedPreferencesHelper.getExportDirectory()
        tvExportDirectorySummary.text = currentDirectory
    }

    private fun setupListeners() {
        llExportDirectory.setOnClickListener {
            openExportDirectorySettings()
        }

        aiProgrammingLayout.setOnClickListener {
            val url = "https://cxyxy.blog.csdn.net/article/details/151590489"
            val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
            startActivity(intent)
        }
    }

    private fun openExportDirectorySettings() {
        openDirectoryPicker()
    }

    private fun openDirectoryPicker() {
        val intent = Intent(Intent.ACTION_OPEN_DOCUMENT_TREE).apply {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                putExtra(DocumentsContract.EXTRA_INITIAL_URI, 
                    Uri.parse(Environment.getExternalStorageDirectory().path))
            }
        }
        directoryPickerLauncher.launch(intent)
    }

    private fun getDirectoryPathFromUri(uri: Uri): String? {
        return try {
            // 尝试获取真实路径
            val path = FileUtils.getPathFromUri(this, uri)
            if (path != null && FileUtils.isDirectoryWritable(path)) {
                path
            } else {
                null
            }
        } catch (e: Exception) {
            null
        }
    }

    override fun onResume() {
        super.onResume()
        // 当从导出目录设置页面返回时，刷新显示的目录
        loadCurrentSettings()
    }

    override fun onSupportNavigateUp(): Boolean {
        finish()
        return true
    }
}